package qplayas

import qplayas.Medioambiente
import com.gargoylesoftware.htmlunit.BrowserVersion

class PlayaJob {

	def playaJobService
	
	static triggers = {
		simple name: 'playaDetailsJob', startDelay: 6000, repeatInterval: 604800000l
	}
	
    def execute() {
		def builder =
			new qplayas.crawling.builder.HtmlUnitBuilder().
				client(BrowserVersion.FIREFOX_3_6) {
				page(url:'http://www.mma.es/portal/secciones/aguas_marinas_litoral/guia_playas/') {
					 println "(B)-->"+currentPage.url
				   elementsByXPath("//select[@id='provincia']/option/@value").findAll{it.value}.each{op->
					   println "----------------------------------------- ${op.value} -----------------------------------"
					 /* PROVINCIAS */
					   form('formulario','envio'){
						   fields {
							   provincia = op.value
						   }
						   page{
							println "(L)-->"+currentPage.url
							//def originPage = currentPage
							/* ---------------------------------------------------------------------------------------------- */
							/* ----------------------------------------- PLAYAS --------------------------------------------- */
							/* ---------------------------------------------------------------------------------------------- */
							   def stillMoreResults = true
							   def paginationPage
							   while(stillMoreResults){
								   if (paginationPage){
									   currentPage = paginationPage
								   }
								   try{
									   currentPage.getFormByName('formsiguientes')
								   } catch (ex){
									   stillMoreResults = false
								   }
								   form('formulario','playa'){
									   fields{}
									   page{
									   	 	def beachName = currentPage.getByXPath("//table[@class='tabla99' and @cellspacing='0' and contains(@summary,'nombre y')]//tr/td/strong")[0].textContent                                     
											def nameLocationProvinceState = currentPage.getByXPath("//table[@class='tabla99' and @cellspacing='0' and contains(@summary,'nombre y')]//tr/td")[0].textContent											
											def beachLocation = nameLocationProvinceState.split(/\n/).findAll{it?.trim()}.collect {it.replaceAll('Playa','').trim()}
											
												def fotosLinkRel = currentPage.getByXPath("//a[@class='negro']/@href")[0].textContent
												def fullUrl = currentPage.getFullyQualifiedUrl(fotosLinkRel).toString()
												def photos = []
												/* Cogemos la pagina actual para volver a ella una vez hemos recuperado las fotos */
												def cp = currentPage
												/* Agregacion de fotos */
												page(url:fullUrl){
													elementsByXPath("//a").each{anchor->
														def fotoUrl = currentPage.
															getFullyQualifiedUrl(
																anchor.hrefAttribute.replaceAll('páginas','images').
																	replaceAll('htm','jpg')
															)														
														photos << fotoUrl.toString()
													}                                         
												}
												
												/* Nos situamos otra vez en la pagina del detalle para coger los datos */
												currentPage = cp
												def beachData = [:] as HashMap							
												def beachNameNormalized = normalizeName(op.value.replaceAll('PR=','').toLowerCase() + beachName)
												def provincia = op.value.replaceAll('PR=','').toLowerCase().capitalize()
												
												beachData.put('beachName',beachLocation[0])
												beachData.put('localidad',beachLocation[1])
												beachData.put('provincia',beachLocation[2])
												beachData.put('comunidad',beachLocation[3])
												/* ------------------------------------------------------------------------------------------------------------------- */
												/* -------------------------------------------------- NORMALIZACION DE NOMBRES --------------------------------------- */
												/* ------------------------------------------------------------------------------------------------------------------- */
												beachData.put('normalizedBeachName',beachNameNormalized)
												beachData.put('normalizedBeachNameSimple',normalizeName(beachName))
												/* ------------------------------------------------------------------------------------------------------------------- */
												/* ------------------------------------------------------------------------------------------------------------------- */
												/* ------------------------------------------------------------------------------------------------------------------- */
												beachData.put('photos',photos)
												currentPage.getByXPath("//table[@class='tabla99' and @cellspacing='3' and contains(@summary,'tabla que muestra caracter')]/child::*/tr/td").each{data->
													if (data.textContent.contains(':')){
														def key = normalizeName((data.textContent.substring(0,data.textContent.indexOf(':')))?.trim())
														def value = data.textContent.substring(data.textContent.indexOf(':')+1)?.trim()											 
														beachData.put(key.toString(),value?.toString()?.trim())															
													}
												}												
												playaJobService.savePlaya(beachData)																				  										 
									   		}
								   		}
								   /* ---------------------------------------------------------------------------------------------- */
								   /* ---------------------------------------------------------------------------------------------- */
								   /* ---------------------------------------------------------------------------------------------- */	
								   try{
									   def form = currentPage.getFormByName('formsiguientes')
									   stillMoreResults = form.actionAttribute 
								   } catch (ex){
									   stillMoreResults = false
								   }
								   if (stillMoreResults){				
									   println "Avanzando de pagina"
									   form('formsiguientes','formsubmit'){
										   fields{}
										   page{
											   println "\tNueva Pagina ${currentPage.url}}"
											   paginationPage = currentPage
										   }   
									   }				   
								   }
							   }//stillMoreResults	
							   //currentPage = originPage					   
						   }
					   }
				   }
				}
			}
    }
}
